package org.gbif.metadata.webapp.action;

import java.net.URLDecoder;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.StringUtils;
import org.appfuse.webapp.action.BaseAction;

/**
 * Proxy action to allow AJAX calls.
 * 
 * @author davejmartin
 */
public class AjaxProxyAction extends BaseAction {

	public String proxyUrl;

	public String responseBody;
	
	public String extraParams ="";
	
	public List<String> allowedHosts;
	
	public String forwardRequest(){
		
		if(StringUtils.isNotBlank(this.proxyUrl)){
			
			HttpClient client = new HttpClient();
			
			try {
				String url = URLDecoder.decode(this.proxyUrl, "UTF-8") +URLDecoder.decode(this.extraParams, "UTF-8");
				log.debug("Request url: "+url);
				GetMethod getMethod = new GetMethod(url);
				int responseCode = client.executeMethod(getMethod);
				log.debug("Response code: "+responseCode);
				this.responseBody = getMethod.getResponseBodyAsString();
				log.debug("Response body: "+this.responseBody);
		     return SUCCESS;
			} catch (Exception e){
				log.error(e.getMessage(),e);
			}
		}
		return ERROR;
	}
	
	public String getProxyUrl() {
		return proxyUrl;
	}

	public void setProxyUrl(String proxyUrl) {
		this.proxyUrl = proxyUrl;
	}

	public String getResponseBody() {
		return responseBody;
	}

	public void setResponseBody(String responseBody) {
		this.responseBody = responseBody;
	}

	public List<String> getAllowedHosts() {
		return allowedHosts;
	}

	public void setAllowedHosts(List<String> allowedHosts) {
		this.allowedHosts = allowedHosts;
	}

	public String getExtraParams() {
		return extraParams;
	}

	public void setExtraParams(String extraParams) {
		this.extraParams = extraParams;
	}
}
